﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
namespace Socket服务器
{
    /// <summary>
    /// AddServer.xaml 的交互逻辑
    /// </summary>
    public partial class AddServer : Window
    {
        public AddServer()
        {
            InitializeComponent();
            InsertIp();
        }

        /// <summary>
        /// 获取IPV4地址
        /// </summary>
        /// <returns></returns>
        List<System.Net.IPAddress> GetLocalIpv4()
        {
            IPAddress[] localIPs;
            localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            List<IPAddress> IPV4 = new List<IPAddress>();
            foreach (IPAddress ip in localIPs)
            {
                //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6  
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    IPV4.Add(ip);
            }
            return IPV4;
        }

        List<System.Net.IPAddress> IPAdress = new List<System.Net.IPAddress>();

        void InsertIp()
        {
            IPAdress = GetLocalIpv4();
            for (int i = 0; i < IPAdress.Count; i++)
            {
                string ip = IPAdress[i].ToString();
                IP.Items.Add(ip);
            }
            if (IP.Items.Count > 0)
                IP.SelectedIndex = 0;
        }

        private void ADD_Click(object sender, RoutedEventArgs e)
        {
            ServerConfig SC = new ServerConfig();
            SC.ServerIP  = IPAdress[IP.SelectedIndex];
            SC.ServerPort =Convert.ToInt16( Port.Text) ;
            SC.DeviceCount  = Convert.ToInt16(TimeOut.Text);
            SC.ServerName = ServerName.Text;
            if (ServerSource.ServerAdd(SC))
            {
                SocketManager ServerView = ServerSource.GetServer(SC.ServerPort);
                ServerSource.Servers.AddServer (ServerView);
                //SocketShow SS = new SocketShow(SC);
                //this.Hide();
                ServerSource.Servers.Show();
            }
            else
            {
                MessageBox.Show("端口已绑定，或服务器名称已存在");
            }
            
        }


        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            
        }
    }
}
